﻿/*
   Copyright 2012 Dmitry Bratus

   Licensed under the Apache License, Version 2.0 (the "License");
   you may not use this file except in compliance with the License.
   You may obtain a copy of the License at

       http://www.apache.org/licenses/LICENSE-2.0

   Unless required by applicable law or agreed to in writing, software
   distributed under the License is distributed on an "AS IS" BASIS,
   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
   See the License for the specific language governing permissions and
   limitations under the License.
*/
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using NLog;
using NLogManager = NLog.LogManager;

namespace Flower.Logging.NLog
{
    public class LogSink : ILogSink
    {
        private readonly Dictionary<string, Logger> _loggers = new Dictionary<string, Logger>();

        private static LogLevel FlowerSeverityToNLog(LoggingLevel level)
        {
            switch (level)
            {
                case LoggingLevel.Fatal:
                    return LogLevel.Fatal;
                case LoggingLevel.Error:
                    return LogLevel.Error;
                case LoggingLevel.Warning:
                    return LogLevel.Warn;
                case LoggingLevel.Info:
                    return LogLevel.Info;
                case LoggingLevel.Trace:
                    return LogLevel.Trace;
                default:
                    throw new ArgumentOutOfRangeException("level");
            }
        }

        public void Dispatch(LogEntry entry)
        {
            Logger logger;

            if (!_loggers.TryGetValue(entry.Source, out logger))
            {
                logger = NLogManager.GetLogger(entry.Source);
                _loggers.Add(entry.Source, logger);
            }

            LogLevel logLevel = FlowerSeverityToNLog(entry.Severity);

            // By some reason NLog ignores \n in the messages, therefore
            // splitting by \n is required.
            if (entry.Exception != null)
            {
                bool first = true;

                foreach (string msg in entry.Message.Split('\n'))
                {
                    if (first)
                    {
                        logger.LogException(logLevel, msg, entry.Exception);
                        first = false;
                    }
                    else
                    {
                        logger.Log(logLevel, msg);
                    }
                }
            }
            else
            {
                foreach (string msg in entry.Message.Split('\n'))
                {
                    logger.Log(logLevel, msg);
                }
            }
        }

        public void Flush()
        {
            //Do nothing.
        }
    }
}
